package com.hu.network.http.interceptor;

import android.support.annotation.NonNull;

import java.io.IOException;

import com.hu.network.http.bodyImpl.RequestBodyImpl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 说明：
 *
 * @author ： hucanhua
 * @date ： 2017/10/28
 */
public class RequestInterceptor implements Interceptor {
    private RequestBodyImpl.ProgressListener progressListener = new RequestBodyImpl.ProgressListener() {
        @Override
        public void progress(long bytesRead, long contentLength, boolean done) {
            System.out.println(bytesRead);
            System.out.println(contentLength);
            System.out.println(done);
            System.out.format("%d%% done%n", 100L * bytesRead / contentLength);
        }
    };
    private String tag;

    public RequestInterceptor() {
    }

    public RequestInterceptor(RequestBodyImpl.ProgressListener progressListener) {
        if (progressListener != null) {
            this.progressListener = progressListener;
        }

    }

    @Override
    public Response intercept(@NonNull Chain chain) throws IOException {
        Request request = chain.request();
        if (request.tag().equals(this.tag)) {
            request = request.newBuilder().post(new RequestBodyImpl(request.body(), this.progressListener)).build();
        }
        return chain.proceed(request);

    }

    public void setTag(String tag) {
        this.tag = tag;
    }
}
